import React, {Component} from 'react';
import fetchJson from '@/utils/fetchJson';
import {connect} from 'react-redux';
import {mapCat, mapGoods} from '@/utils/tools';
// 左侧菜单
import LeftMenu from '@/components/LeftMenu';
import Toast from '@/components/Toast';
import Loading from '@/components/Loading';
import GoodCell from '@/components/GoodCell';

document.title = '分类';
class Catalog extends Component {
  constructor (...args) {
    super(...args);
    this.state = {
      keyword: '',
      storeID: this.props.storeInfo.storeID,
      categoryID: 'all',
      isFocus: true,
      fromStatus: 1,
      toStatus: 1,
      offset: 0,
      pageSize: 10,
      page: 1,
      goods: [],
      totalCount: 0,
      catList: [],
      loading: false,
      noMore: false,
      noGoods: false
    }
  }
  async componentDidMount () {
    // 添加滚动监听
    this.refs.rightGoods.addEventListener('scroll', this.goodsScroll.bind(this));
    document.title = '分类';
    await this.setState({loading: true});
    await this.getCat();
    await this.getGoods();
    await this.setState({loading: false});
    console.log('数据获取完成');
  }
  // 从服务器获取门店商品数据
  async getGoods (type) {
    // 处理筛选条件
    let json = {};
    json.keyword = this.state.keyword;
    json.storeID = this.state.storeID;
    if (this.state.categoryID !== 'all') json.categoryID = this.state.categoryID;
    json.isFocus = this.state.isFocus;
    json.fromStatus = this.state.fromStatus;
    json.toStatus = this.state.toStatus;
    json.offset = this.state.offset;
    json.pageSize = this.state.pageSize;
    let arr = [];
    if (type === 'append') {
      this.setState(prevState => {page: ++prevState.page});
    } else {
      this.refs.rightGoods.scrollTop = 0;
      this.setState({page: 1, goods: []});
    }
    json.offset = (this.state.page - 1) * json.pageSize;
    for (let attr in json) {
      arr.push(`${attr}=${json[attr]}`);
    }
    let query = arr.join('&');
    console.log(query);
    this.setState({noGoods: false, noMore: false});
    let {totalCount, skuNames} = await fetchJson('v2/store/sku/GetStoreSkus?' + query);

    console.log('获取到的商品', totalCount, skuNames);
    if (!skuNames) {
      this.setState({noGoods: true});
      return false;
    }
    if (type === 'append') {
      this.setState(prevState => {
        return {
          totalCount,
          goods: [...prevState.goods, ...mapGoods(skuNames)]
        };
      });
    } else {
      this.setState({
        totalCount,
        goods: mapGoods(skuNames)
      });
    }
  }
  // 从服务器获取分类
  async getCat () {
    try {
      let data = await fetchJson('v2/sku/GetCategories');
      console.log('获取到的分类', data);
      this.setState({
        catList: mapCat(data)
      });
    } catch (e) {
      console.log(e);
      this.refs.toast.showToast(e);
    }
  }
  // 设置关键字
  setKeyword () {
    this.setState({
      keyword: this.refs.inputKeyWord.value
    });
  }
  // 清除关键字
  async fnClear () {
    this.setState({
      keyword: ''
    });
    await this.setState({loading: true});
    await this.getGoods();
    await this.setState({loading: false});
  }
  // 通过关键字检索
  async fnKeyWordSearch (e) {
    console.log(e.charCode)
    if (e.charCode === 13) {
      // 敲击回车
      this.refs.leftMenu.fnClick('all', 1);
      await this.setState({loading: true});
      await this.getGoods();
      await this.setState({loading: false});
      this.refs.inputKeyWord.blur();
    }
  }
  // 失去焦点
  async fnBlur () {
    this.refs.leftMenu.fnClick('all', 1);
    await this.setState({loading: true});
    await this.getGoods();
    await this.setState({loading: false});
  }
  // 菜单ID变化
  async getCatID (ID) {
    console.log('目前分类ID ', ID);

    if (ID !== 'all') {
      // 清空关键字
      await this.setState({
        categoryID: ID,
        keyword: ''
      });
    } else {
      await this.setState({
        categoryID: ID
      });
    }
    await this.setState({loading: true});
    await this.getGoods();
    await this.setState({loading: false});
  }
  // 滚动
  async goodsScroll (e) {
    let scrollTop = e.target.scrollTop;
    let scrollH = e.target.scrollHeight;
    let divH = e.target.offsetHeight;
    // scrollH = scrollTop + divH;
    if (scrollH - divH <= scrollTop + 100) {
      if (this.state.pageSize * this.state.page >= this.state.totalCount) {
        // 没有更多了
        this.setState({noMore: true});
      } else {
        // 还可以请求
        await this.setState({loading: true});
        await this.getGoods('append');
        await this.setState({loading: false});
      }
    }
  }
  render () {
    // console.log()
    return (
      <div className="catalog">
        {/* 检索框 */}
        <div className="search">
          <input value={this.state.keyword} ref="inputKeyWord" type="text" onChange={this.setKeyword.bind(this)} placeholder="搜索店内商品" onKeyPress={this.fnKeyWordSearch.bind(this)}/>
          <span className="search-icon"></span>
          {
            this.state.keyword ? (
              <span className="clear-icon" onClick={this.fnClear.bind(this)}></span>
            ) : ''
          }
        </div>
        {/* 主体 */}
        <div className="content">
          {/* 左侧菜单 */}
          <LeftMenu ref="leftMenu" catList={this.state.catList} getCatID={this.getCatID.bind(this)}></LeftMenu>
          {/* 右侧商品 */}
          <div className="right" ref="rightGoods" style={{overflowY: this.state.loading ? 'hidden' : 'auto'}}>
            {
              this.state.goods.length > 0 ? (
                this.state.goods.map(good => (
                  <GoodCell
                    key={good.id}
                    good={good}
                  ></GoodCell>
                ))
              ) : ''
            }
            {
              this.state.goods.length === 0 && this.state.page === 1 && this.state.noGoods ? <div className="no-goods">暂时没有商品，敬请期待</div> : ''
            }
            {
              this.state.noMore && this.state.goods.length > 0 ? (
                <div className="no-goods">到底啦，别拉啦~</div>
              ) : ''
            }
          </div>
        </div>
        {/* toast */}
        <Toast ref="toast"></Toast>
        {/* loading */}
        {
          this.state.loading ? <Loading></Loading> : ''
        }
      </div>
    )
  }
}

export default connect((state, props) => Object.assign({}, props, state), {})(Catalog);
